import React, { useEffect, useMemo, useState } from 'react';
import { useQuery, gql, useLazyQuery, useMutation } from '@apollo/client';
import { Space, Table, TableProps,Button,message as Message, Modal } from 'antd';
import { AccountModal } from '../components/AccountModal';

const AccountListGql = gql`
  query AccountList { # 定义查询方法(浏览器上显示的)
    accountList { # 定义与后端对接的方法名
      id
      username
      password
    }
  }
`;
const DeleteAccountGql = gql`
  mutation DeleteAccount($id:ID!) {
    deleteAccountById(id: $id) {
      code
      message
    }
  }
`;


export const Home = () => {
  const [getAccount, { loading, data }] = useLazyQuery(AccountListGql);
  const [currentRow, setCurrentRow] = useState<any>()
  const [modalVisible, handleModalVisible] = useState<boolean>(false);
  const [deleteAccount] = useMutation(DeleteAccountGql, {
    onCompleted: (data) => {
      console.log(data)
      // const { modifyAccountById: { code, message } } = data;
      // if (Object.is(code, 0)) {
      //   Message.success(message);
      // } else {
      //   Message.error(message);
      // }
    }
  })
  const accountList = useMemo(() => {
      return data?.accountList || []
  }, [data])
  useEffect(() =>{
    getAccount();
  }, [])
  const columns: TableProps<any>['columns'] = [
     {
         title: 'ID',
         dataIndex: 'id'
     },{
         title: '用户名',
         dataIndex: 'username'
     },
     {
        title: '密码',
        dataIndex: 'password'
    },
    {
        title: 'Action',
        key: 'action',
        render: (text, record) => (
          <Space size="middle">
            <Button onClick={() => {
              setCurrentRow(record);
              handleModalVisible(true)
               }}>编辑</Button>
            <Button danger onClick={() => {
              Modal.confirm({
                title: '确定删除该用户?',
                onOk: () => deleteAccount({variables:{ id: record.id}})
              })
            }}>删除</Button>
          </Space>
        ),
      },
  ]
  console.log(data)
  return <>
  <AccountModal isModalVisible={modalVisible} setIsModifyVisible={handleModalVisible} currentRowId={currentRow?.id} loadData={() =>getAccount()}></AccountModal>
  <Table rowKey='id' loading={loading} dataSource={accountList} columns={columns}>
  </Table></>
}